unit uCorretorPedidoVenda;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  Formulario_Padrao_Rel, RDprint, ExtCtrls, StdCtrls, CheckLst, ComCtrls,
  Buttons, db, dbtables, Gauges, TFlatButtonUnit;

type
  TfrmCorrigePedVenda = class(TFrmPad_Rel)
    pb: TGauge;
    procedure bimprimirClick(Sender: TObject);
    procedure btncancelarClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    function RecuperaEntidade(ped: string): string;
  end;

var
  frmCorrigePedVenda: TfrmCorrigePedVenda;

implementation

uses Dm;

{$R *.DFM}

procedure TfrmCorrigePedVenda.bimprimirClick(Sender: TObject);
var
  tq, tq1: TQuery;
begin
  inherited;
  pb.MinValue := 0;
  pb.MaxValue := 0;
  pb.Progress := 0;

  tq := Tquery.Create(dmint);
  tq.databasename := dmint.db.databasename;
  tq1 := Tquery.Create(dmint);
  tq1.databasename := dmint.db.databasename;

  tq.active := False;
  tq.sql.Clear;
  tq.params.clear;
  tq.sql.add('select Ped_Numero, Ped_Item from itempedvenda ' +
    'where ent_codigo is null');
  tq.open;
  pb.MaxValue := tq.RecordCount;
  while not tq.Eof do begin
    pb.Progress := pb.Progress + 1;
    tq1.active := False;
    tq1.sql.Clear;
    tq1.params.clear;
    tq1.sql.add('Update ItemPedVenda set Ent_Codigo =:Ent ' +
      'where Ped_Numero =:Ped and Ped_Item = :Item');
    tq1.ParamByName('Ped').AsString := tq.FieldByName('Ped_Numero').AsString;
    tq1.ParamByName('Item').AsString := tq.FieldByName('Ped_Item').AsString;
    tq1.ParamByName('Ent').AsString := RecuperaEntidade(tq.FieldByName('Ped_Numero').AsString);
    try
      tq1.ExecSQL;
    except
      ShowMessage('Erro ao alterar pedido!');
    end;
    tq.Next;
  end;
  ShowMessage('Processo Finalizado!');
  tq.Close;
  tq.Free;
  tq1.Close;
  tq1.Free;
  pb.Progress := 0;
end;

function TfrmCorrigePedVenda.RecuperaEntidade(ped: string): string;
var
  tq: TQuery;
begin
  tq := Tquery.Create(dmint);
  tq.databasename := dmint.db.databasename;
  tq.active := False;
  tq.sql.Clear;
  tq.params.clear;
  tq.sql.add('Select Ent_Codigo from PedidosVenda ' +
    'where Ped_Numero =:Ped and Ent_Codigo is not null');
  tq.ParamByName('ped').AsString := ped;
  tq.open;
  Result := '';
  if not tq.Eof then
    Result := tq.FieldByName('Ent_Codigo').AsString;
  tq.Close;
  tq.Free;

end;

procedure TfrmCorrigePedVenda.btncancelarClick(Sender: TObject);
begin
  inherited;
  pb.Progress := 0;
end;

end.
